import { useState } from "react";
import { Form, Input, Select, Button, DatePicker, Modal, message } from "antd";
import { useNavigate } from "react-router-dom";
import styles from "./AddInandoutofStorage.module.css";

interface InandoutofStorageData {
  team: string;
  typeof: string;
  warehouseName: string;
  createTime: string;
  endTime: string;
  productType: string;
  productSKU: string;
  productName: string;
  num: number;
  shelfNumber: string;
  containerNumber: string;
  inboundordernumber: string;
  outordernumber: string;
  countordernumber: string;
  remark: string;
  proStatus: number;
}

const AddInandoutofStorage: React.FC = () => {
  const [form] = Form.useForm();
  const { RangePicker } = DatePicker;
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 提交表单
  const onFinish = async (values: any) => {
    console.log("=== 开始提交表单 ===");
    console.log("原始表单数据:", values);
    
    setLoading(true);
    try {
      const formData: InandoutofStorageData = {
        ...values,
        createTime: values.timeRange[0].format("YYYY-MM-DDTHH:mm:ss.SSSZ"),
        endTime: values.timeRange[1].format("YYYY-MM-DDTHH:mm:ss.SSSZ"),
        num: Number(values.num),
        proStatus: Number(values.proStatus)
      };

      console.log("处理后的提交数据：", formData);

      const response = await fetch("http://localhost:5233/api/InandoutofStorage/AddInandoutofStorage", {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(formData)
      });

      console.log("响应状态：", response.status);
      console.log("响应头：", response.headers);
      
      if (!response.ok) {
        console.error("HTTP错误:", response.status, response.statusText);
        throw new Error(`HTTP错误: ${response.status}`);
      }
      
      // 解析响应数据
      const responseData = await response.json();
      console.log("响应数据：", responseData);

      if (responseData.code === 200) {
        console.log("进入成功分支");
        
        // 显示成功提示
        message.success('添加成功！', 2);
        
        console.log("准备显示确认框");
        
        // 使用简单的confirm确保跳转功能正常
        const shouldNavigate = confirm('数据添加成功！是否立即跳转到查询页面？');
        
        if (shouldNavigate) {
          console.log("用户选择跳转");
          console.log("navigate函数:", navigate);
          console.log("准备跳转到:/InandoutofStorageQuery");
          
          try {
            navigate('/InandoutofStorageQuery');
            console.log("跳转调用成功");
          } catch (error) {
            console.error("跳转失败:", error);
          }
        } else {
          console.log("用户选择不跳转，清空表单");
          form.resetFields();
        }
        
      } else {
        console.log("进入失败分支，code:", responseData.code);
        throw new Error(responseData.message || '提交失败');
      }
    } catch (error: any) {
      console.error("=== 提交错误 ===");
      console.error("错误类型:", error.constructor.name);
      console.error("错误信息:", error.message);
      console.error("完整错误:", error);
      
      message.error(`添加失败：${error.message}`);
      Modal.error({
        title: '添加失败',
        content: `添加数据时发生错误：${error.message}`,
        okText: '确定'
      });
    } finally {
      console.log("=== 提交结束，设置loading为false ===");
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <Form
        form={form}
        onFinish={onFinish}
        className={styles.form}
      >
        <Form.Item
          name="team"
          label="团队"
          rules={[{ required: true, message: "请选择团队" }]}
        >
          <Select placeholder="请选择团队">
            <Select.Option value="南京团队<>">南京团队</Select.Option>
            <Select.Option value="苏州1号团队<>">苏州1号团队</Select.Option>
            <Select.Option value="杭州团队<>">杭州团队</Select.Option>
            <Select.Option value="厦门团队<>">厦门团队</Select.Option>
            <Select.Option value="北京团队<>">北京团队</Select.Option>
            <Select.Option value="上海团队<>">上海团队</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="typeof"
          label="类型"
          rules={[{ required: true, message: "请选择类型" }]}
        >
          <Select placeholder="请选择类型">
            <Select.Option value="入库">入库</Select.Option>
            <Select.Option value="出库">出库</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="warehouseName"
          label="仓库"
          rules={[{ required: true, message: "请选择仓库" }]}
        >
          <Select placeholder="请选择仓库">
            <Select.Option value="仓库A">仓库A</Select.Option>
            <Select.Option value="仓库B">仓库B</Select.Option>
            <Select.Option value="仓库C">仓库C</Select.Option>
            <Select.Option value="仓库D">仓库D</Select.Option>
            <Select.Option value="仓库E">仓库E</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="timeRange"
          label="时间范围"
          rules={[{ required: true, message: "请选择时间范围" }]}
        >
          <RangePicker showTime />
        </Form.Item>

        <Form.Item
          name="productType"
          label="产品类型"
          rules={[{ required: true, message: "请输入产品类型" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="productSKU"
          label="产品SKU"
          rules={[{ required: true, message: "请输入产品SKU" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="productName"
          label="产品名称"
          rules={[{ required: true, message: "请输入产品名称" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="num"
          label="数量"
          rules={[{ required: true, message: "请输入数量" }]}
        >
          <Input type="number" placeholder="1" />
        </Form.Item>

        <Form.Item
          name="shelfNumber"
          label="货架号"
          rules={[{ required: true, message: "请输入货架号" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="containerNumber"
          label="集装箱号"
          rules={[{ required: true, message: "请输入集装箱号" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="inboundordernumber"
          label="入库单号"
          rules={[{ required: true, message: "请输入入库单号" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="outordernumber"
          label="出库单号"
          rules={[{ required: true, message: "请输入出库单号" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="countordernumber"
          label="清点单号"
          rules={[{ required: true, message: "请输入清点单号" }]}
        >
          <Input placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="remark"
          label="备注"
          rules={[{ required: true, message: "请输入备注" }]}
        >
          <Input.TextArea placeholder="请输入" />
        </Form.Item>

        <Form.Item
          name="proStatus"
          label="状态"
          initialValue="0"
          rules={[{ required: true, message: "请选择状态" }]}
        >
          <Select placeholder="请选择状态">
            <Select.Option value="0">正常</Select.Option>
            <Select.Option value="1">异常</Select.Option>
          </Select>
        </Form.Item>

        <Form.Item>
          <Button 
            type="primary" 
            htmlType="submit" 
            className={styles.submitButton}
            loading={loading}
          >
            提交
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
};

export default AddInandoutofStorage;
